<template>
  <div class="count-down">
    <small>{{ data.days }}</small>
    天
    <small>{{ data.hours }}</small>
    :
    <small>{{ data.minutes }}</small>
    :
    <small>{{ data.seconds }}</small>
  </div>
</template>


<script setup>
// 引入CompositionAPI
import {computed, onMounted, ref} from 'vue'

// 引用声明
const props = defineProps({
  time: {
    type: [String],
    default: () => ""
  }
});

// 引用事件
const emits = defineEmits(['end'])


const useCountDown = (end_time) => {
  // 时间秒
  const timeout = ref(0);

  // 时间实例
  const Timer = ref(null);

  // 查看
  if (typeof end_time === 'string') {
    end_time = new Date(end_time).getTime()
  }

  // 结束时间戳 - 当前时间戳 ，毫秒转为秒
  timeout.value = end_time - Date.now() / 1000;

  // 定时方法
  const close = () => {
    if (Timer.value) clearInterval(Timer.value)
  }

  // 关闭定时
  close()

  // 声明周期
  onMounted(() => {
    Timer.value = setInterval(() => {
      timeout.value--;
      if (timeout.value <= 0) {
        close()
        emits('end')
      }
    }, 1000)
  });


  // 计算属性
  const d = computed(() => formatDiffDate(timeout.value))


  // 返回值
  return d;
}


// 将秒 转化为 天/时/分/秒
const formatDiffDate = (timeout) => {
  let time = {
    days: 0,
    hours: 0,
    minutes: 0,
    seconds: 0
  };

  if (timeout > 0) {
    time.days = Math.floor(timeout / (60 * 60 * 24));
    time.hours = Math.floor(timeout / (60 * 60)) - (time.days * 24);
    time.minutes = Math.floor(timeout / 60) - (time.days * 24 * 60) - (time.hours * 60);
    time.seconds = Math.floor(timeout) - (time.days * 24 * 60 * 60) - (time.hours * 60 * 60) - (time.minutes * 60);
  }

  // // 手动三元补零
  time.days = time.days < 10 ? '0' + time.days : time.days;
  time.hours = time.hours < 10 ? '0' + time.hours : time.hours;
  time.minutes = time.minutes < 10 ? '0' + time.minutes : time.minutes;
  time.seconds = time.seconds < 10 ? '0' + time.seconds : time.seconds;
  return time

  return time;
}


// 调用方法
const data = useCountDown(props.time);
</script>

<style>
.count-down small {
  background-color: white;
  border-radius: 2px;
  padding: 2px 3px;
  margin: 0 3px;
  @apply text-yellow-500;
}
</style>
